package cn.flying.cloud.base.dubbo.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import cn.flying.cloud.base.common.constants.Constants;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.utils.lang.StringUtil;

/**
 * dubbo调用设置公用的参数
 *
 * @author: admin
 * @date: 2022年12月25日 11:38
 * @version: 1.0
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, order = -900000, value = "header")
public class HeaderFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Make sure call invoker.invoke() in your implementation.
     *
     * @param invoker
     * @param invocation
     */
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcContext context = RpcContext.getContext();
        String traceId = context.getAttachment(Constants.TRAC_ID);
        if (StringUtils.isBlank(traceId)) {
            // consumer 设置到上下文
            context.setAttachment(Constants.TRAC_ID, MDC.get(Constants.TRAC_ID));
        } else {
            // provider 设置traceId到上下文
            MDC.put(Constants.TRAC_ID, traceId);
        }
        // 设置当前租户Id
        String tenantId = context.getAttachment(Constants.TENANT_ID);
        if (StringUtils.isBlank(tenantId)) {
            context.setAttachment(Constants.TENANT_ID, Ft.Local.TenantId());
        }
        // 设置当前用户Id
        String userId = context.getAttachment(Constants.USER_ID);
        if (StringUtils.isBlank(userId)) {
            context.setAttachment(Constants.USER_ID, Ft.Local.UserId());
        }
        // 设置当前用户名
        String userName = context.getAttachment(Constants.USER_NAME);
        if (StringUtils.isBlank(userName)) {
            context.setAttachment(Constants.USER_NAME, Ft.Local.UserName());
        }
        // 请求者Id
        String requestId = context.getAttachment(Constants.REQUEST_ID);
        if (StringUtil.isBlank(requestId)) {
            context.setAttachment(Constants.REQUEST_ID, Ft.Local.RequestId());
        }
        // 环境
        String envId = context.getAttachment(Constants.ENV_ID);
        if (StringUtil.isBlank(envId)) {
            context.setAttachment(Constants.ENV_ID, Ft.Local.EnvId());
        }
        logger.info("当前链路请求ID：[{}]，租户：[{}]，用户ID：[{}]，用户名：[{}]", MDC.get(Constants.TRAC_ID), Ft.Local.TenantId(), Ft.Local.UserId(), Ft.Local.UserName());
        return invoker.invoke(invocation);
    }
}
